#include <cstdlib>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include "projection.h"
#include "minIni.h"
#include "config.h"
#include "resources.h"
#include "map.h"
#include "spriteanimator.h"
#include "sprite.h"
#include "blitqueue.h"
#include "grcontext.h"
#include "entityaction.h"
#include "entity.h"
#include "entitymanager.h"

using namespace Oribi;

EntityManager::~EntityManager()
{
    for (int i = 0; i < (int)entities.size(); ++i)
    {
        delete entities[i];
    }
}

void EntityManager::updateEntities()
{
    int m = entities.size();
    for (int i = 0; i < m; ++i)
    {
        if (entities[i])
            entities[i]->update();
    }
}

Entity *EntityManager::addEntity(const Entity& ent)
{
    unsigned i;
    Entity *res = ent.clone();
    for (i = 0; i < entities.size(); ++i)
    {
        if (!entities[i])
        {
            entities[i] = res;
            break;
        }
    }
    if (i == entities.size())
        entities.push_back(res);

    return res;
}

bool EntityManager::removeEntity(const Entity* ent)
{
    if (!ent)
        return false;

    for (unsigned i = 0; i < entities.size(); ++i)
    {
        if (entities[i] == ent)
        {
            entities[i] = NULL;
            return true;
        }
    }

    return false;
}

void EntityManager::drawEverything(GraphicContext& gr)
{
    int m = entities.size();
    for (int i = 0; i < m; ++i)
    {
        if (entities[i])
            entities[i]->blit(gr);
    }

}
